package com.snail.utils;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;

import com.alipay.api.response.AlipayTradeRefundResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
public class PayUtil {
    // 支付宝配置参数
    private final String APP_ID = "9021000151612912";
    private final String APP_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCSnbBdfJ51MAM1WY7kad5ktmcb/dSenzmfwJ2EJHNl/7cBQm+QRzwYWxkXORUxv1NuIVCHVQ4ZR7PCt09kDeLP2PE7VRLClVEFiJDU33ecWR3gp+u9KXU0q6nHlIVt3hjVIDtV0NSqQXJhFRiCdgdAcwTraHri00+aVQYSK0j5SX2rAyTgEzpQSUpIoOnB00yFkXgiJxDYGt+ROPIecLqzEspy+jCu1GI/NZWsfVL6mi8Dqj7iJuFUaUiyKckjMWsAXK3SStSWqx5r8FGtwtKF4/ZuCoTv49c74ov1AYsvrQnlNSZo95CJ3+uXU+qdgd/9OSqk5+rhizNeGWODKFU9AgMBAAECggEBAISVFGd1ydUvFbeoxQ7IrdNlHtixMRQ/6FwOUmKsk64pD9STv085G57qwkW92Oyjl05/0dKPl7BEpsnt+l0AMZrDE2IUDGLpo9rdJBtb+U3pSJtfPk5QryxyD5XrOL2hmdMg0odH0QglJsmjygYvtV8So+A9GuMDM3jcaiEEA3lpGzhJ1DJhXYov3Kwv4Hs/KuluNPsFqTT9NkiSaobvClrvcM41oAjPRm8bWe80QwDA105G1yzkYPMP31Q6kAIYaoW+FOC2wwL1tWSljBfXvlCucO2m6iiGZ1kQj2ZqYvc6H5CgNj0uswE0tSnKZUwXjXQ4ENI3z/cTGc7GIXY2AgECgYEA2EGyPJnRbYKAaTxsByEE4cIWXayx3j5hvK47xybBaZwLd4B7y55F2UTV1GFPf7IgzKAew+bnvmm6wSivDLSMrMLPhU+LmrCAteoLsWdW+bokOylQmwtB3h3z20V3AQA8rgVOaigJ4OALgZ9KJQ542FitwucxEmIoz0mAQZh/JS8CgYEArY+VajncjDN2mm4EuhQ6n6sLSHL+Kg2rZyWT5KNBNjr+s/596ydMZVJrDP9eQ9lSTMKEIXZKIon8sAU4gY+k06yDFzzAuwgzkHrdgQvvEZJULrTdeU7b9fCg1KoJ8kPFaNJbGC/nrCOTfOmqDVc0UsnXr5Ng/v/JKQxxZAGBaVMCgYEA1XOq6NPuegfYlYbVHghCWE8JYnalrbanI+RaDo07VPF4BAEmr+lOClE+Of2+yUzZwP++viB412JmumdcuM6xF4jF6lCEfDABKw2TcwyMNbu8LUTvUcm/vuyTmPesqalBO4bzSiaw8WxTDyNZvM/XCbwl7n3h2sJWg5uJ47UQsnMCgYEAgGpeWOxa3HkvZe/FG5DgF0dM39wFZkQa8ASDuoV4OJHJ5o+DxzuacNVcU4+WxYjENfsuHDwTeh6ykeIq/uGzSNK5Y7YVu8zDqkDeJx8XUd783loADENmyD+0H+V32oJ+S6JouCqptVnVRHT210wQcLjbFxNqjwHearrEIwRiJfUCgYAXFNEkdi9mfPUVXXAPoyAmLdbUa0PQQDtQ/coQmzMcfNG5JCnnsZRncaJJnHDwwUUy7zEh5EJggePNRIunExpX7X1TavcSP6SE9ZxqkSuqz91Dlu9YizvljifTjRT16eFgTJWUtEuAoJxah8wbPHAyNBJxXwEWQM2af/xRl6aDWQ==";
    private final String CHARSET = "UTF-8";
    private final String ALIPAY_PUBLIC_KEY = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAobYDKnEhHjfG5ajt84L9qiz0jTjcKn/GxiUGh3Xd0cwRlxHObqonumIhwUBAXX9CjSrbgzW3Ox8LRl38nTuvtN+HH4XvyzBljEiHdU/HcedEjnk8B0yiWdLMp4KfIPZq9XW0V+H4NNq1hYu7QDLMoTwNglEgxyazISlgWUfeqYq1EQutqmN2rQDbkVxSoflTTTu1sF8fWNRVryluyM+bzEsFqjHd19HZfil4OrFWXv/1UuioqYodjkDftBUpguI0uFFKSLIuJy1HYIEzvXu0dNERAc+oPydlV/Z901SfzvUooZehy5qv5F6MfOR+UNInCtISWbuo4+f2Q8kehoTnrwIDAQAB";
    private final String GATEWAY_URL = "https://openapi-sandbox.dl.alipaydev.com/gateway.do";
    private final String FORMAT = "JSON";
    private final String SIGN_TYPE = "RSA2";
    private final String NOTIFY_URL = " ha69c8d6.natappfree.cc/mall/alipay/notify";
//private final String NOTIFY_URL = "http://localhost:9527/mall/api/alipay/notify";
//    private final String RETURN_URL = "http://localhost:9527/mall/api/alipay/return";
    private final String RETURN_URL ="http://localhost:5173/";
    private AlipayClient alipayClient;
    
    public PayUtil() {
        this.alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
    }

    /**
     * 创建支付宝支付页面
     * @param outTradeNo 商户订单号
     * @param totalAmount 支付金额
     * @param subject 订单标题
     * @return 支付页面表单HTML
     */
    public String createOrder(String outTradeNo, String totalAmount, String subject) throws AlipayApiException {
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(RETURN_URL);
        alipayRequest.setNotifyUrl(NOTIFY_URL);

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("product_code", "FAST_INSTANT_TRADE_PAY");
        bizContent.put("total_amount", totalAmount);
        bizContent.put("subject", subject);
        
        alipayRequest.setBizContent(bizContent.toJSONString());

        String s = alipayClient.pageExecute(alipayRequest).getBody();
        System.out.println(s);
        return s;
    }
    public String refund(String outTradeNo, String refundAmount, String refundReason) throws AlipayApiException {
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();

        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        bizContent.put("refund_amount", refundAmount);
        bizContent.put("refund_reason", refundReason);

        request.setBizContent(bizContent.toJSONString());

        AlipayTradeRefundResponse response = alipayClient.execute(request);
        return response.getBody();
    }
    /**
     * 查询订单状态
     * @param outTradeNo 商户订单号
     * @return 订单查询结果
     */
    public String queryOrder(String outTradeNo) throws AlipayApiException {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        JSONObject bizContent = new JSONObject();
        bizContent.put("out_trade_no", outTradeNo);
        request.setBizContent(bizContent.toString());
        
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        return response.getBody();
    }

    public boolean verifyNotification(Map<String, String> params) {
        try {
            return AlipaySignature.rsaCheckV1(
                    params,
                    ALIPAY_PUBLIC_KEY,
                    CHARSET,
                    SIGN_TYPE
            );
        } catch (AlipayApiException e) {
            e.printStackTrace();
            return false;
        }
    }


}